import { Form, Input, TreeSelect } from 'antd'
import PropTypes from 'prop-types'
import { findOneArticle, createArticle, updateArticle } from '@/api/article'
import { useEffect, useState } from 'react'
import ArticleEditor from '@/components/ArticleEditor'
import ArticleLook from '@/components/ArticleLook'
import { forwardRef } from 'react'
import { useImperativeHandle } from 'react'

const ArticleForm = forwardRef((props, ref) => {
  const [form] = Form.useForm()
  const [content, setContent] = useState('')

  useEffect(() => {
    async function fetchData () {
      if (props.article_id) {
        const { data } = await findOneArticle({
          id: props.article_id
        })

        form.setFieldsValue(data)
        setContent(data.content)
      }
    }
    fetchData()
  }, [form, props.article_id])

  const onOk = async () => {
    const values = await form.validateFields()

    if (props.article_id) {
      //更新
      await updateArticle({
        id: props.article_id,
        ...values
      })
    } else {
      //新增
      await createArticle(values)
    }
  }

  useImperativeHandle(ref, () => ({
    confirm: onOk
  }))

  return (
    <Form
      form={form}
      autoComplete="off"
      disabled={props.isDetail}
      labelCol={{ span: 4 }}
    >
      <Form.Item
        name="category_id"
        label="文章分类"
        rules={[
          {
            required: true,
            message: '请选择文章分类'
          }
        ]}
      >
        <TreeSelect
          showSearch
          allowClear
          treeNodeFilterProp='name'
          fieldNames={{
            label: 'name',
            value: 'category_id',
            children: 'children'
          }}
          treeData={props.treeData}
        />
      </Form.Item>
      <Form.Item
        name="title"
        label="文章标题"
        rules={[
          {
            required: true,
            message: '请输入文章标题'
          }
        ]}
      >
        <Input />
      </Form.Item>
      <Form.Item
        name="content"
        label="文章内容"
        rules={[
          {
            required: true,
            message: '请输入文章内容'
          }
        ]}
      >
        {
          props.isDetail ?
            <ArticleLook content={content} /> :
            <ArticleEditor content={content} onBlur={(v) => {
              setContent(v)
              form.setFieldsValue({ content: v })
            }} />
        }
      </Form.Item>
    </Form>
  )
})

ArticleForm.displayName = 'ArticleForm'

ArticleForm.propTypes = {
  article_id: PropTypes.number,
  treeData: PropTypes.array.isRequired,
  isDetail: PropTypes.bool
}

export default ArticleForm